﻿using AutoMapper;
using MediatR;
using MyMES.Domain.yjb;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Writer.API.Application.Commends.settingCommand;
using MyMES.Writer.API.FileNlog;

namespace MyMES.Writer.API.Application.CommendHandlers.settingCommand
{
    public class AddWorkOrderInfoCommandHandlers : IRequestHandler<AddWorkOrderInfoCommand, APIResult<WorkOrderInfo>>
    {
        private readonly IBaseRepository<WorkOrderInfo> accreop;
        private readonly IMapper mapper;
        private readonly Nolgs nlogs;

        public AddWorkOrderInfoCommandHandlers(IBaseRepository<WorkOrderInfo> accreop, IMapper mapper, Nolgs nlogs)
        {
            this.accreop = accreop;
            this.mapper = mapper;
            this.nlogs = nlogs;
        }
        /// <summary>
        /// 仓库-添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<WorkOrderInfo>> Handle(AddWorkOrderInfoCommand request, CancellationToken cancellationToken)
        {
            var startTime = DateTime.Now;
            try
            {
                APIResult<WorkOrderInfo> result = new APIResult<WorkOrderInfo>();
                result.Code = APIEnum.添加成功;
                result.Msg = "添加成功";
                var model = mapper.Map<WorkOrderInfo>(request);
                string sql = "insert into WorkOrderInfo(WorkOrderInfoId,WorkOrderCode, WorkOrderName, WorkOrderSource, OrderNumber, ProductCode, ProductName, SpecificationModel, Unit,WorkOrderQuantity,AdjustedQuantity,ProducedQuantity,CustomerCode,CustomerName,DemandDate,SchedulingStatus,Remarks,IsDelete) values(@WorkOrderInfoId,@WorkOrderCode, @WorkOrderName, @WorkOrderSource, @OrderNumber, @ProductCode, @ProductName, @SpecificationModel, @Unit,@WorkOrderQuantity,@AdjustedQuantity,@ProducedQuantity,@CustomerCode,@CustomerName,@DemandDate,@SchedulingStatus,@Remarks,@IsDelete)";
                await accreop.Insert(model, sql);
                return result;
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                var endTime = System.DateTime.Now;

                var durationInDays = (endTime - startTime).Days;
                nlogs.GetNlogs(
                    request.CustomerName ?? "Unknow", "仓库添加", "False", durationInDays, "异常信息"
                    );
            }
        }
    }
}
